package com.chenyi.web.controller.api;

import com.alipay.api.AlipayApiException;
import com.chenyi.common.annotation.RepeatSubmit;
import com.chenyi.common.core.domain.ApiError;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.pay.bean.AlipayBean;
import com.chenyi.pay.bean.WxpayBean;
import com.chenyi.pay.exception.WxPayApiException;
import com.chenyi.pay.service.PayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import javax.jms.Destination;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Api(description = "测试模块")
@RestController
@RequestMapping("/api/test")
public class ApiTestController {

    @Autowired
    private RedissonClient redissonClient;

    @ApiOperation("防止重复提交")
    @GetMapping("/getSubmit")
    @RepeatSubmit
    public ResponseEntity<Object> getSubmit(){

        return ResponseEntity.ok("FFF");
    }

    private int num = 10;

    @ApiOperation("测试Redis锁")
    @GetMapping("/getRedis")
    public ResponseEntity<Object> getRedis(){
        RLock rLock = redissonClient.getLock("GET_REDIS_TEST");
        try {
            //加锁 操作很类似Java的ReentrantLock机制
            rLock.lock();
            if (num > 0){
                num--;
                System.out.println("抢购成功,剩余数量："+num);
                return ResponseEntity.ok("抢购成功,剩余数量："+num);
            }
            System.out.println("抢购失败");
            return ResponseEntity.ok("抢购失败");
        }finally {
            //解锁
            rLock.unlock();
        }
    }


    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;


    @PostMapping("/queue/test")
    public ResponseEntity<Object> sendQueue(@RequestBody String str) {
        Destination destination = new ActiveMQQueue("active.queue");
        this.sendMessage(destination, str);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/topic/test")
    public ResponseEntity<Object> sendTopic(@RequestBody String str) {
        Destination destination = new ActiveMQTopic("active.topic");
        this.sendMessage(destination, str);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 的controller是单例模式，但是是多线程，各个线程之间不影响
     */
    @PostMapping("/sleepTest")
    public ResponseEntity<Object> sleepTest(@RequestBody String str){
        try {
            System.out.println("正在执行："+str);
            Thread.sleep(5000);
            System.out.println("释放："+str);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Autowired
    private PayService payService;

    @RepeatSubmit
    @PostMapping("/aliPayAsWeb")
    public ResponseEntity<Object> aliPayAsWeb(){
        try {
            String result = payService.aliPayAsWeb(new AlipayBean()
                    .setOut_trade_no(new Date().getTime() + "")
                    .setBody("支付测试")
                    .setTotal_amount("0.01")
                    .setSubject("支付测试")
            );
            return ResponseEntity.ok(result);
        }catch (AlipayApiException exception){
            throw new BadRequestException(exception.getErrCode(),exception.getErrMsg());
        }
    }

    @RepeatSubmit
    @PostMapping("/aliPayAsApp")
    public ResponseEntity<Object> aliPayAsApp(){
        try {
            String result = payService.aliPayAsApp(new AlipayBean()
                    .setOut_trade_no(new Date().getTime() + "")
                    .setBody("支付测试")
                    .setTotal_amount("0.01")
                    .setSubject("支付测试")
            );
            return ResponseEntity.ok(result);
        }catch (AlipayApiException exception){
            throw new BadRequestException(exception.getErrCode(),exception.getErrMsg());
        }
    }

    @RepeatSubmit
    @PostMapping("/wxPayAsApp")
    public ResponseEntity<Object> wxPayAsApp(){
        try {
            String result = payService.wxPayApp(new WxpayBean()
                    .setOut_trade_no(new Date().getTime() + "")
                    .setBody("支付测试")
                    .setTotal_fee("1")
            );
            return ResponseEntity.ok(result);
        }catch (WxPayApiException exception){
            throw new BadRequestException(exception.getStatus(),exception.getMessage());
        }
    }

    @RepeatSubmit
    @PostMapping("/wxPayAsMiniapp")
    public ResponseEntity<Object> wxPayAsMiniapp(){
        try {
            String result = payService.wxPayAsMiniapp(new WxpayBean()
                    .setOut_trade_no(new Date().getTime() + "")
                    .setBody("支付测试")
                    .setTotal_fee("1")
                    .setOpenid("oAuDKwaCMEbWa51DS0wL7fhzpNw8")
            );
            return ResponseEntity.ok(result);
        }catch (WxPayApiException exception){
            throw new BadRequestException(exception.getStatus(),exception.getMessage());
        }
    }

    // 发送消息，destination是发送到的队列，message是待发送的消息
    private void sendMessage(Destination destination, final String message){
                jmsMessagingTemplate.convertAndSend(destination, message);
    }
 }
